var _n10;
var cc__extends = __extends;
var cc__decorate = __decorate;
var cc__awaiter = __awaiter;
var cc__generator = __generator;
var cc__importDefault = __importDefault;
Object.defineProperty(exports, "__esModule", {
  value: true
});
var cc__decorator = cc._decorator;
var ccp_ccclass = cc__decorator.ccclass;
var ccp_property = cc__decorator.property;
function d(t) {
  for (let o = t.length - 1; o > 0; o--) {
    const n = Math.floor(Math.random() * (o + 1));
    // Swap elements at indices n and o
    [t[o], t[n]] = [t[n], t[o]];
  }
  return t;
}
var h = ["#6ccae2", "#95ed85", "#206abc", "#ef8bfb", "#d7c55e", "#7043bd", "#ff6e8d"];
var $1$GameUILayer = require("GameUILayer");
var f = cc__importDefault($1$GameUILayer);
var $1$TargetMgr = require("TargetMgr");
var y = cc__importDefault($1$TargetMgr);
var $1$EffectLayer = require("EffectLayer");
var g = cc__importDefault($1$EffectLayer);
var $1$LevelsConfig = require("LevelsConfig");
var v = cc__importDefault($1$LevelsConfig);
var $1$PaintBoard = require("zqcc_PaintBoard");
var m = cc__importDefault($1$PaintBoard);
var $1$ResourceLoader = require("ResourceLoader");
var _ = cc__importDefault($1$ResourceLoader);
var $zqcc_OverallSystem = require("zqcc_OverallSystem");
var $1$Board = require("Board");
var b = cc__importDefault($1$Board);
var def_GamePlay = function (t) {
  function _ctor() {
    const e = null !== t && t.apply(this, arguments) || this;

    // Initializing properties to null or appropriate default values
    e.gameUILayer = null;
    e.targetMgr = null;
    e.effectLayer = null;
    e.objPrefab = null;
    e.levelRoot = null;
    e.blockLayer = null;
    e.boardBaffle = null;
    e.paintBoard = null;
    e.level = 1; // Default level set to 1
    e.boardLayer = null;
    e.boards = []; // Initialize as an empty array

    return e; // Return the initialized object
  }
  cc__extends(_ctor, t);
  _ctor.prototype.onLoad = function () {
    // Enable physics and collision managers
    cc.director.getPhysicsManager().enabled = true;
    cc.director.getCollisionManager().enabled = true;

    // Set gravity for the physics manager
    cc.director.getPhysicsManager().gravity = cc.v2(0, -1600);

    // Event listener for button click
    cc.game.on("btn_remove_board", this.showBlockLayer, this);

    // Initialize the game UI layer
    this.gameUILayer.init(this);

    // Set up touch event listeners
    this.blockLayer.on(cc.Node.EventType.TOUCH_START, this.onBlockLayerTouchStart, this);
    this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);

    // Get the RigidBody component from the board baffle and bind contact event
    const rigidBodyComponent = this.boardBaffle.getComponent(cc.RigidBody);
    if (rigidBodyComponent) {
      rigidBodyComponent.onBeginContact = this.onBeginContact.bind(this);
    }
  };
  _ctor.prototype.initPhysics = function (t) {
    var e = t;
    cc.game.config.groupList = e["group-list"];
    cc.game.config.collisionMatrix = e["collision-matrix"];
    cc.game._initConfig(cc.game.config);
  };
  _ctor.prototype.onAutoPlay = function () {
    if (cc.director.getScheduler().isScheduled(this.startAutoPlay, this)) {
      this.unschedule(this.startAutoPlay);
    } else {
      this.schedule(this.startAutoPlay, .2);
    }
  };
  _ctor.prototype.startAutoPlay = function () {
    // 开始自动播放，输出日志
    cc.log("startAutoPlay");

    // 遍历所有棋盘，从后向前循环
    for (let boardIndex = this.boards.length - 1; boardIndex >= 0; boardIndex--) {
      const currentBoard = this.boards[boardIndex];

      // 检查棋盘是否未锁定
      if (!currentBoard.isLocked) {
        const screwComponents = currentBoard.getScrewComps();

        // 遍历所有螺丝组件
        for (let componentIndex = 0; componentIndex < screwComponents.length; componentIndex++) {
          const currentComponent = screwComponents[componentIndex];

          // 检查组件未锁定并且触摸事件可以启用
          if (!currentComponent.isLocked && this.isTouchenEnabled(currentBoard, currentComponent)) {
            // 执行触摸操作
            return void this.touchOperateObj(currentComponent);
          }
        }
      }
    }
  };
  _ctor.prototype.initGame = function (t, e) {
    return cc__awaiter(this, undefined, Promise, function () {
      return cc__generator(this, function (o) {
        switch (o.label) {
          case 0:
            // 输出游戏开始日志
            cc.log("gamePlay");
            // 初始化绘画板并等待其完成
            return [4, this.initPaintBoard(t)];
          case 1:
            o.sent();  // 等待initPaintBoard的执行结束
            // 初始化棋盘并等待其完成
            return [4, this.initBoards()];
          case 2:
            o.sent();  // 等待initBoards的执行结束
            // 刷新棋盘的锁定状态
            this.refreshBoardLockState();
            // 初始化关卡配置并等待其完成
            return [4, this.initLevelConfig(t, e)];
          case 3:
            o.sent();  // 等待initLevelConfig的执行结束
            return [2];  // 结束函数执行
        }
      });
    });
  };
  _ctor.prototype.showBlockLayer = function () {
    this.blockLayer.active = true;
  };
  _ctor.prototype.getColorConfig = function (t, e) {
    // 获取绘画板的步骤
    var steps = this.paintBoard.zqcc_getSteps();
    var colorIndices = [];

    // 遍历步骤，收集颜色索引
    for (var i = 0; i < steps.length; i++) {
      var step = steps[i];
      colorIndices.push(step.colorIndex);
    }

    var levelConfig = null;

    // 检查是否有远程关卡配置并更新全局配置
    if (window.RemoteLevelConfig && (window.wx || window.tt)) {
      Object.assign(v.default, window.RemoteLevelConfig);
    }

    // 根据参数e选择关卡难度
    if (e) {
      levelConfig = v.default.LevelDifficulty[t] || v.default.LevelDifficulty.normal;
    } else {
      levelConfig = v.default.LevelDifficulty.dae;
    }

    var numColors = colorIndices.length;
    var colorGroups = [];
    var currentIndex = 0;

    // 根据关卡配置分组颜色索引
    for (i = 1; i < levelConfig.length; i++) {
      var previousLevel = levelConfig[i - 1];
      var gap = levelConfig[i][0] - previousLevel[0];
      var count = Math.floor(gap * numColors);

      // 处理最后一个分组的索引
      if (i === levelConfig.length - 1) {
        count = numColors - currentIndex;
      }

      var colorGroup = [];
      for (var f = currentIndex; f < currentIndex + count; f++) {
        colorGroup.push(colorIndices[f]);
      }

      currentIndex += count;
      colorGroups.push(colorGroup);
    }

    // 输出颜色索引和颜色分组
    cc.log("colors", colorIndices);
    cc.log("colorArr", colorGroups);
    return colorGroups;
  };
  _ctor.prototype.initLevelConfig = function (t, e) {
    var context = this;
    return new Promise(function (resolve) {
      // 获取颜色配置
      var colorConfig = context.getColorConfig(t, e);
      var expandedColors = [];
      var originalColors = [];

      // 遍历颜色配置并扩展颜色
      for (var i = 0; i < colorConfig.length; i++) {
        var colorGroup = colorConfig[i];
        var expandedGroup = [];

        // 扩展每个颜色组中的颜色
        for (var j = 0; j < colorGroup.length; j++) {
          for (var k = 0; k < 3; k++) {
            expandedGroup.push(colorGroup[j]);
          }
        }

        // 合并扩展后的颜色和原始颜色
        Array.prototype.push.apply(expandedColors, d(expandedGroup));
        Array.prototype.push.apply(originalColors, colorGroup);
      }

      // 设置目标管理器的数据
      context.targetMgr.setData(originalColors, context);

      // 遍历棋盘并为每个螺丝组件设置类型
      for (var boardIndex = context.boards.length - 1; boardIndex >= 0; boardIndex--) {
        var screwComponents = context.boards[boardIndex].getScrewComps();
        for (var componentIndex = 0; componentIndex < screwComponents.length; componentIndex++) {
          screwComponents[componentIndex].setType(expandedColors.shift());
        }
      }

      // 解析Promise
      resolve();
    });
  };
  _ctor.prototype.initPaintBoard = function (t) {
    return cc__awaiter(this, undefined, undefined, function () {
      var jsonData;
      return cc__generator(this, function (o) {
        switch (o.label) {
          case 0:
            // 加载指定的JSON资源
            return [4, _.default.getInstance().load("Feibiao", "rope/json/lv_" + t, cc.JsonAsset)];
          case 1:
            jsonData = o.sent();  // 等待加载完成
            cc.log("+++++++", jsonData.json);  // 输出加载的JSON数据
            // 将加载的数据应用到绘画板
            this.paintBoard.zqcc_loadGridData(jsonData.json);
            return [2];  // 结束函数执行
        }
      });
    });
  };
  _ctor.prototype.initBoards = function () {
    var context = this;
    this.boards = [];
    return new Promise(function (resolve) {
      // 创建并扩展颜色数组
      var colorArray = h.concat([]);
      var expandedColors = (colorArray = d(colorArray)).concat(colorArray).concat(colorArray);

      // 定义处理每个棋盘的函数
      var processBoard = function (boardIndex) {
        var board = context.boardLayer.children[boardIndex];

        // 根据Y坐标排序当前棋盘的子节点
        board.children.sort(function (a, b) {
          return b.y - a.y;
        });

        // 在一定延迟后处理每个子节点
        context.scheduleOnce(function () {
          for (var childIndex = 0; childIndex < board.children.length; childIndex++) {
            var child = board.children[childIndex];

            // 获取和配置刚体组件
            var rigidBody = child.getComponent(cc.RigidBody);
            rigidBody.enabledContactListener = true;
            rigidBody.angularDamping = 2;

            // 获取其他组件
            var customComponent = child.getComponent(b.default);
            var physicsCollider = child.getComponent(cc.PhysicsPolygonCollider);
            var polygonCollider = child.getComponent(cc.PolygonCollider);

            // 设置棋盘层级和默认组
            customComponent.layerIndex = boardIndex + 1;
            child.group = "default";

            // 复制碰撞点，并初始化组件
            physicsCollider.points = polygonCollider.points;
            physicsCollider.apply();
            customComponent.init(context.objPrefab);

            // 设置棋盘颜色
            customComponent.setBoardColor(cc.Color.WHITE.fromHEX(expandedColors[boardIndex % expandedColors.length]));

            // 将棋盘添加到数组
            context.boards.push(customComponent);
          }

          // 处理完成，若为最后一个棋盘则解析Promise
          if (boardIndex + 1 === context.boardLayer.children.length) {
            resolve();
          }
        }, 0.01 * boardIndex); // 延迟时间
      };

      // 遍历所有棋盘并处理
      for (var boardIndex = 0; boardIndex < context.boardLayer.children.length; boardIndex++) {
        processBoard(boardIndex);
      }
    });
  };
  _ctor.prototype.refreshBoardLockState = function () {
    var availableBoards = [];

    // 创建可用棋盘数组
    for (var i = 1; i <= 20; i++) {
      var boardName = "board_" + i;
      availableBoards.push(boardName);
    }

    // 遍历棋盘层，移除已使用的棋盘名称
    for (var layerIndex = this.boardLayer.children.length - 1; layerIndex >= 0; layerIndex--) {
      var layer = this.boardLayer.children[layerIndex];
      if (layer.children.length > 0) {
        var firstChild = layer.children[0];
        var boardIndex = availableBoards.indexOf(firstChild.group);
        if (boardIndex >= 0) {
          availableBoards.splice(boardIndex, 1); // 移除已占用的棋盘
        }
      }
    }

    var activeCount = 0;

    // 重新遍历棋盘层，设置锁定状态与组
    for (layerIndex = this.boardLayer.children.length - 1; layerIndex >= 0; layerIndex--) {
      var layer = this.boardLayer.children[layerIndex];
      if (layer.children.length > 0) {
        activeCount++; // 统计当前激活的棋盘数量
      }

      var newGroup = "";
      for (var childIndex = 0; childIndex < layer.children.length; childIndex++) {
        var child = layer.children[childIndex];
        var component = child.getComponent(b.default);

        // 根据激活数量设置锁定状态
        if (activeCount > 5) {
          component.setLock(true, 0);
        } else if (activeCount > 4) {
          component.setLock(true);
        } else {
          // 选择新的组
          if (newGroup === "") {
            newGroup = availableBoards.splice(0, 1)[0];
          }
          if (child.group === "default" && availableBoards.length > 0) {
            var collider = child.getComponent(cc.Collider);
            collider.enabled = false; // 禁用碰撞体以避免问题
            child.group = newGroup; // 设置新的组
            collider.enabled = true; // 重新启用碰撞体
          }
          component.setLock(false); // 解除锁定
        }
      }
    }
  };
  _ctor.prototype.getTopObjs = function (t) {
    // 如果t未定义，设为1
    undefined === t && (t = 1);

    // 过滤出未锁定的棋盘并按层级索引降序排序
    var unlockedBoards = this.boards.filter(function (board) {
      return !board.isLocked;
    }).sort(function (boardA, boardB) {
      return boardB.layerIndex - boardA.layerIndex;
    });

    var screwTypes = [];
    var currentLayerIndex = -1; // 当前层级索引
    var layerCount = 0; // 当前层计数

    // 遍历所有未锁定的棋盘
    for (var board of unlockedBoards) {
      // 如果层级索引发生变化，增加层计数
      if (currentLayerIndex !== board.layerIndex) {
        currentLayerIndex = board.layerIndex; // 更新当前层索引
        if (++layerCount > t) {
          break; // 达到目标层数后结束循环
        }
      }

      // 获取每个棋盘的螺丝组件类型并添加到数组
      board.getScrewComps().forEach(function (screw) {
        screwTypes.push(screw.type);
      });
    }

    return screwTypes; // 返回收集到的螺丝类型
  };
  _ctor.prototype.isTouchenEnabled = function (t, e) {
    // 遍历所有棋盘
    for (var index = 0; index < this.boards.length; index++) {
      var board = this.boards[index];

      // 检查棋盘是否未锁定且不是指定棋盘同时层级索引大于指定值，并判断是否发生碰撞
      if (!board.isLocked && t !== board && !(board.layerIndex <= t.layerIndex) && this.isCollided(e.sprite, board)) {
        return false; // 如果条件满足，返回false
      }
    }

    // 如果没有发生碰撞，返回true
    return true;
  };
  _ctor.prototype.isCollided = function (t, e) {
    var o = t.getComponent(cc.PolygonCollider).world.points;
    var n = e.node.getComponent(cc.PolygonCollider).world.points;
    return cc.Intersection.polygonPolygon(o, n);
  };
  _ctor.prototype.onBlockLayerTouchStart = function (t) {
    var context = this;
    cc.log("touch block layer");

    // 获取触摸位置
    var touchLocation = t.getLocation();
    cc.log("touchLoc", touchLocation);

    // 定义处理每个棋盘的函数
    var checkBoard = function (boardIndex) {
      var board = i.boards[boardIndex];

      // 如果棋盘被锁定，则继续
      if (board.isLocked) {
        return "continue";
      }

      // 获取棋盘的碰撞体世界坐标点
      var polygonPoints = board.node.getComponent(cc.PolygonCollider).world.points;

      // 检查触摸点是否在棋盘的多边形内
      if (cc.Intersection.pointInPolygon(touchLocation, polygonPoints)) {
        // 播放锤子效果
        i.effectLayer.playHammerEffect(board.node);

        // 移除触摸事件
        i.blockLayer.off(cc.Node.EventType.TOUCH_START, i.onBlockLayerTouchStart, i);

        // 在0.5秒后处理后续逻辑
        i.scheduleOnce(function () {
          context.blockLayer.active = false; // 关闭块层
          context.blockLayer.on(cc.Node.EventType.TOUCH_START, context.onBlockLayerTouchStart, context); // 重新添加触摸事件

          // 触发移除棋盘事件
          cc.game.emit("remove_board", board);
          $zqcc_OverallSystem.mgrs().soundMgr.playSound("板子碎"); // 播放碎板声效
        }, 0.5);

        return {
          value: undefined
        };
      } else {
        return undefined; // 返回未定义表示未触摸到棋盘
      }
    };

    var i = this; // 缓存当前上下文

    // 从后向前遍历所有棋盘
    for (var boardIndex = this.boards.length - 1; boardIndex >= 0; boardIndex--) {
      var result = checkBoard(boardIndex);
      if (typeof result === "object") {
        return result.value; // 返回结果
      }
    }

    // 如果未选中任何棋盘，显示提示消息
    this.node.getComponent("Feibiao").showMessage("请选择一块板子敲碎");
  };
  _ctor.prototype.onTouchStart = function (t) {
    // 获取触摸位置
    var touchLocation = t.getLocation();

    // 从后向前遍历所有棋盘
    for (var boardIndex = this.boards.length - 1; boardIndex >= 0; boardIndex--) {
      var board = this.boards[boardIndex];
      var screwComponents = board.getScrewComps();

      // 遍历当前棋盘的所有螺丝组件
      for (var compIndex = 0; compIndex < screwComponents.length; compIndex++) {
        var screw = screwComponents[compIndex];

        // 检查螺丝组件是否未锁定
        if (!screw.isLocked) {
          // 获取螺丝组件的碰撞体世界坐标点
          var colliderPoints = screw.sprite.getComponent(cc.PolygonCollider).world.points;

          // 检查触摸点是否在螺丝组件的多边形内
          if (cc.Intersection.pointInPolygon(touchLocation, colliderPoints)) {
            // 检查触摸是否启用
            if (this.isTouchenEnabled(board, screw)) {
              // 进行触摸操作
              return void this.touchOperateObj(screw);
            } else {
              // 播动效果并播放声音
              screw.shake();
              return void $zqcc_OverallSystem.mgrs().soundMgr.playSound("wufayidong");
            }
          }
        }
      }
    }
  };
  _ctor.prototype.touchOperateObj = function (t) {
    this.targetMgr.onTouchOperateObj(t);
    cc.game.emit("screw_remove", t);
    $zqcc_OverallSystem.mgrs().soundMgr.playSound("点击飞镖");
    $zqcc_OverallSystem.sers().platformSrv.platformApi.vibrateShort(false);
  };
  _ctor.prototype.onBeginContact = function (t, e, o) {
    // 禁用当前对象和触发的事件
    o.enabled = false;
    t.disabled = true;

    // 查找当前棋盘在boards数组中的索引
    var boardIndex = this.boards.indexOf(o.node.getComponent("Board"));
    if (boardIndex > -1) {
      cc.log("移出板子"); // 输出移除棋盘的日志信息

      // 从父节点中移除该棋盘
      o.node.removeFromParent(true);

      // 从boards数组中移除该棋盘
      this.boards.splice(boardIndex, 1);

      // 刷新棋盘的锁定状态
      this.refreshBoardLockState();
    }
  };
  cc__decorate([ccp_property(f.default)], _ctor.prototype, "gameUILayer", undefined);
  cc__decorate([ccp_property(y.default)], _ctor.prototype, "targetMgr", undefined);
  cc__decorate([ccp_property(g.default)], _ctor.prototype, "effectLayer", undefined);
  cc__decorate([ccp_property(cc.Prefab)], _ctor.prototype, "objPrefab", undefined);
  cc__decorate([ccp_property(cc.Node)], _ctor.prototype, "levelRoot", undefined);
  cc__decorate([ccp_property(cc.Node)], _ctor.prototype, "blockLayer", undefined);
  cc__decorate([ccp_property(cc.Node)], _ctor.prototype, "boardBaffle", undefined);
  cc__decorate([ccp_property(m.default)], _ctor.prototype, "paintBoard", undefined);
  cc__decorate([ccp_property], _ctor.prototype, "level", undefined);
  return cc__decorate([ccp_ccclass], _ctor);
}(cc.Component);
exports.default = def_GamePlay;